import Vue from 'vue';
import config from './config.js';
import store from '@/store/index.js';

import {RouterMount,createRouter} from 'uni-simple-router';

// 初始化
const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,  
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	//权限控制操作
	//console.info(store.store);
	let cacheData = uni.getStorageSync('cacheData') || undefined;
	let token = '';
	if(cacheData){
		 token = cacheData.vuex_token ? cacheData.vuex_token : '';
	}
	console.info('路由拦截：' + to.meta.auth + ' token：' + token)
	if (to.meta && to.meta.auth) {
		//如果token不为空，判断是否有效
		if (token) {
			console.info('有token，校验token');
			//校验token是否有效
			uni.request({
				url: config.baseUrl + '/api/login/check',
				method: 'GET',
				header: {
					'Authorization': token
				},
				success: (res) => {
					console.log(res.data);
					if(res.data.code == 200){
						next();
					}else{
						uni.setStorageSync('cacheData', '');
						//next('/pages/login/login');
						next({path:'/pages/login/login',NAVTYPE: 'push'});
					}
				}
			});
		}else{
			console.info('不存在token，去登陆');
			//next('/pages/login/login');
			next({path:'/pages/login/login',NAVTYPE: 'push'});
		}
	} else {
		console.info('存在token：' + token + ' 名称：' + to.meta.name);
		if (token && to.meta.name == "login") {
			console.info('去首页。。。')
			//next('/pages/index/index',NAVTYPE: 'push');
			next({path:'/pages/index/index',NAVTYPE: 'push'});
		} else {
			console.info('next。。。')
			next();
		}
	}

})
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log(to, "全局路由后置守卫");
})
export {
	router,
	RouterMount
}
